package observermall

import "fmt"

// SubscriptionManager 订阅管理
type SubscriptionManager struct {
	users    map[string]Observer
	products map[string]*Product
}

func NewSubscriptionManager() *SubscriptionManager {
	return &SubscriptionManager{
		users:    make(map[string]Observer),
		products: make(map[string]*Product),
	}
}

// RegisterUser 注册用户
func (m *SubscriptionManager) RegisterUser(user Observer) {
	m.users[user.GetID()] = user
}

// AddProduct 添加产品
func (m *SubscriptionManager) AddProduct(product *Product) {
	m.products[product.ID] = product
}

// Subscribe 订阅
func (m *SubscriptionManager) Subscribe(userID, productID string) {
	user, ok := m.users[userID]
	if !ok {
		fmt.Printf("用户 %s 不存在\n", userID)
		return
	}

	product, ok := m.products[productID]
	if !ok {
		fmt.Printf("产品 %s 不存在\n", productID)
		return
	}

	product.Register(user)
}

// Unsubscribe 取消订阅
func (m *SubscriptionManager) Unsubscribe(userID, productID string) {
	user, ok := m.users[userID]
	if !ok {
		fmt.Printf("用户 %s 不存在\n", userID)
		return
	}

	product, ok := m.products[productID]
	if !ok {
		fmt.Printf("产品 %s 不存在\n", productID)
		return
	}

	product.Deregister(user)
}
